import Vue from 'vue';
import Router from 'vue-router';
import { turnTo } from '../libs/util';
import routes from './routes';
import store from '../store';

Vue.use(Router);

const router = new Router({
    // mode: 'history', // hash
    routes,
});

router.beforeEach((to, from, next) => {
    const title = to.meta && to.meta.title;
    if (title) {
        document.title = title;
    }
    const userInfo = store.getters['user/userInfo'];
    if (userInfo.token) {
        // turnTo(to, userInfo.access, next);
        // 无匹配路由时跳转home页.
        if (to.matched.length === 0) {
            next({ name: 'home' }); // 路径错跳转home页面
        } else {
            next();
        }
    } else if (to.path === '/' || to.path === '/login') {
        next();
    } else {
        next({
            path: '/',
            query: { redirect: to.fullPath }, // 将跳转的路由path作为参数，登录成功后跳转到该路由
        });
    }
});

export default router;
